package web.vo;

import framework.pid.PidOption;
import framework.pid.PidUtil;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import system.entity.SysFunc;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 菜单选项
 */
public class MenuOption implements PidOption {

    /**
     * 清理无权限功能项
     *
     * @param permissions
     * @param funcList
     */
    public static void cleanNoPermission(List<String> permissions, List<SysFunc> funcList) {
        Set<String> map = new HashSet<>(permissions);
        map.add("AUTH");
        map.add("ANON");
        for (int i = funcList.size() - 1; i >= 0; i--) {
            SysFunc func = funcList.get(i);
            if (func.getPermissionId() == null) continue;
            String[] items = func.getPermissionId().split(",");
            boolean has = false;
            for (String item : items) {
                if (map.contains(item)) {
                    has = true;
                    break;
                }
            }
            if (!has) {
                funcList.remove(i);
            }
        }
    }

    @Override
    public Long order() {
        if (func.getOrderNum() == null) return 0L;
        return Long.valueOf(func.getOrderNum());
    }

    @Override
    public String pid() {
        if (func.getPid() == null) return "";
        return String.valueOf(func.getPid());
    }

    @Override
    public String id() {
        return String.valueOf(func.getId());
    }

    @Getter
    private SysFunc func;

    @Getter
    private List<PidOption> children = new ArrayList<>();

    public MenuOption(SysFunc func) {
        this.func = func;
    }

    public static List<MenuOption> tree(List<SysFunc> list, boolean clearChildEmpty) {
        List<MenuOption> optionList = new ArrayList<>();
        for (SysFunc func : list) {
            optionList.add(new MenuOption(func));
        }
        //
        optionList = PidUtil.tree(optionList, "-", false);
        if (clearChildEmpty) {
            PidUtil.cleanNonChildren(optionList, i ->
                            //清理子目录且子节点为空的节点
                            (i.func.getFunType() != null && i.func.getFunType() == 0)
//                        && (i.func.getFunPath() != null && i.func.getFunPath().endsWith("/"))
                                    && (StringUtils.isBlank(i.func.getFunView()) || "/".equals(i.func.getFunView()))
                                    && i.getChildren().size() == 0
            );
        }
        return optionList;
    }
}
